package com.lsl.rdf.config;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.util.Assert;

import java.util.List;

/**
 * Created by lsl on 2021/4/27.
 */
@Slf4j
public class RedissonConfig {

    private RedisProperties redisProperties;

    public RedissonConfig(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    /**
     * 创建单机RedissonClient实例
     *
     * @return RedissonClient
     */
    public RedissonClient createSingle() {
        Config config = new Config();
        config
                .useSingleServer()
                .setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setDatabase(redisProperties.getDatabase())
                .setUsername(redisProperties.getUsername())
                .setPassword(redisProperties.getPassword());
        return Redisson.create(config);
    }

    /**
     * 创建集群RedissonClient实例
     *
     * @return RedissonClient
     */
    public RedissonClient createCluster() {
        Config config = new Config();
        RedisProperties.Cluster cluster = redisProperties.getCluster();
        Assert.notNull(cluster, "createCluster RedissonClient 创建失败，Cluster配置为空，请检查配置！");

        List<String> nodes = cluster.getNodes();
        String[] nodeArr = new String[nodes.size()];
        for (int j = 0; j < nodes.size(); j++) {
            nodeArr[j] = "redis://" + nodes.get(j);
        }
        config
                .useClusterServers()
                .setScanInterval(2000)
                .setUsername(redisProperties.getUsername())
                .setPassword(redisProperties.getPassword())
                .addNodeAddress(nodeArr);
        return Redisson.create(config);
    }
}
